import { ElMessage } from "element-plus"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { usePersonaStore } from "@/pinia/stores/persona"

// 配置数据接口
interface AudienceConfig {
  workflowId: string
  workflowName: string
  primaryAudience: string
  activeTime: string
  contentPreference: string
  lastUpdateTime: string
}

export function useAudienceConfig(personaId: string) {
  const router = useRouter()
  const personaStore = usePersonaStore()
  const loading = ref(false)
  const hasExistingConfig = ref(false)

  // 配置数据
  const configData = reactive<AudienceConfig>({
    workflowId: "",
    workflowName: "",
    primaryAudience: "",
    activeTime: "",
    contentPreference: "",
    lastUpdateTime: ""
  })

  // 填入示例数据
  const fillDemoData = () => {
    configData.workflowId = "WF_AUDIENCE_FOOD_EXPERT"
    configData.workflowName = "餐饮专家人设受众分析流"
    configData.primaryAudience = "25-40岁的美食爱好者和餐饮从业者，关注专业技巧和行业内容，对品质有较高要求。"
    configData.activeTime = "工作日：12:00-14:00, 18:00-21:00；周末：11:00-15:00, 17:00-22:00。"
    configData.contentPreference = "专业技巧分享、行业内幕揭秘、食材选购指南、经营心得、与同行交流。"
    configData.lastUpdateTime = new Date().toISOString().split("T")[0]

    ElMessage.success("示例数据填入成功")
  }

  // 保存配置
  const saveConfig = async () => {
    // 验证必填字段
    if (!configData.workflowId || !configData.workflowName) {
      ElMessage.error("请填写工作流ID和名称")
      return
    }

    if (!configData.primaryAudience || !configData.activeTime || !configData.contentPreference) {
      ElMessage.error("请填写受众画像预设信息")
      return
    }

    try {
      loading.value = true

      // TODO: 调用保存配置API
      // await saveAudienceConfig(personaId, configData)

      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000))

      ElMessage.success("受众画像配置保存成功")

      // 更新人设状态
      personaStore.updatePersonaConfig(personaId, true)

      // 保存成功后返回列表页面
      goBack()
    } catch (error) {
      console.error("保存配置失败:", error)
      ElMessage.error("保存配置失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 返回列表页面
  const goBack = () => {
    router.push("/persona-maintenance")
  }

  // 初始化数据
  const init = async () => {
    try {
      loading.value = true

      // TODO: 调用获取现有配置API
      // const response = await getAudienceConfig(personaId)
      // if (response.data) {
      //   Object.assign(configData, response.data)
      //   hasExistingConfig.value = true
      // }

      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
      console.error("获取配置失败:", error)
    } finally {
      loading.value = false
    }
  }

  // 页面加载时初始化
  init()

  return {
    loading,
    configData,
    hasExistingConfig,
    fillDemoData,
    saveConfig,
    goBack,
    init
  }
}
